<template>
  <div class="draft-notice-container">
    <!-- 查询表单 -->
    <div class="search-form">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="公告编号">
              <el-input v-model.number="searchForm.id" placeholder="请输入" type="number" clearable @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公告标题">
              <el-input v-model="searchForm.title" placeholder="请输入" clearable @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <el-select v-model="searchForm.deptId" placeholder="请选择" clearable filterable>
                <el-option v-for="dept in deptOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择" clearable>
                <el-option label="未发布" :value="0" />
                <el-option label="已撤销" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="showAddDialog">新增</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 公告表格 -->
    <div class="notice-table">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="公告编号" align="center" />
        <el-table-column prop="deptId" label="部门" align="center">
          <template #default="scope">
            {{ getDeptName(scope.row.deptId) }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="公告标题" min-width="350" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" link @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" link type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status === 1">编辑</el-button>
            <el-button size="small" link type="success" @click="handlePublish(scope.row)" :disabled="scope.row.status === 1">发布</el-button>
            <el-button size="small" link type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.status === 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size" :total="pagination.total" layout="total, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" :close-on-click-modal="false" align-center>
      <el-form :model="noticeForm" :rules="rules" ref="noticeFormRef" label-width="80px">
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="noticeForm.deptId" placeholder="请选择部门" style="width: 100%">
            <el-option v-for="dept in deptOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="noticeForm.title" placeholder="请输入公告标题" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="noticeForm.content" type="textarea" :rows="8" placeholder="请输入公告内容" maxlength="1000" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" v-if="dialogType === 'add'">保存</el-button>
          <el-button type="success" @click="handlePublishDialog" v-if="dialogType === 'add'">发布</el-button>
          <el-button type="primary" @click="handleEditSubmit" v-if="dialogType === 'edit'">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看公告对话框 -->
    <el-dialog v-model="viewDialogVisible" width="50%" align-center>
      <div class="notice-detail-container">
        <h3 class="notice-title">{{ currentNotice.title }}</h3>
        <div class="notice-meta">
          <span class="dept-name">发布部门：{{ currentNotice.deptName }}</span>
          <span class="status">状态：{{ currentNotice.status }}</span>
        </div>
        <el-divider />
        <div class="notice-content" v-html="currentNotice.content"></div>
      </div>
      <template #footer>
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
    
    <script>
import { getAllDepts } from "../../api/dept";
import {
  getDraftNotices,
  publishNotice,
  viewNoticeContent,
  editNotice,
  changeNoticeStatus,
  deleteNotice,
} from "../../api/notice";

export default {
  name: "DraftNotice",
  data() {
    return {
      searchForm: {
        id: null,
        title: "",
        deptId: null,
        status: null,
      },
      deptOptions: [],
      tableData: [],
      loading: false,
      pagination: {
        current: 1,
        size: 10,
        total: 0,
      },
      dialogVisible: false,
      viewDialogVisible: false,
      dialogType: "add", // 'add' or 'edit'
      dialogTitle: "新增公告",
      noticeForm: {
        id: null,
        deptId: null,
        title: "",
        content: "",
      },
      currentNotice: {
        title: "",
        content: "",
      },
      rules: {
        deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
        title: [
          { required: true, message: "请输入公告标题", trigger: "blur" },
          { max: 20, message: "标题长度不能超过20个字符", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入公告内容", trigger: "blur" },
          { max: 1000, message: "内容长度不能超过1000个字符", trigger: "blur" },
        ],
      },
      currentNotice: {
        title: "",
        content: "",
        deptName: "",
        status: "",
      },
    };
  },
  created() {
    this.initData();
  },
  methods: {
    // 初始化数据
    async initData() {
      await this.fetchDepts();
      await this.fetchData();
    },

    // 获取部门列表
    async fetchDepts() {
      try {
        const res = await getAllDepts();
        this.deptOptions = res.result || [];
      } catch (error) {
        console.error("获取部门列表失败:", error);
        this.$message.error("获取部门列表失败");
      }
    },

    // 获取表格数据
    async fetchData() {
      this.loading = true;
      try {
        const params = {
          id: this.searchForm.id || undefined,
          title: this.searchForm.title || undefined,
          deptId: this.searchForm.deptId || undefined,
          status:
            this.searchForm.status !== null
              ? this.searchForm.status
              : undefined,
          pageNum: this.pagination.current,
          pageSize: this.pagination.size,
        };

        const res = await getDraftNotices(params);
        this.tableData =
          res.result?.records || res.result?.list || res.result || [];
        this.pagination.total = res.result?.total || res.result?.length || 0;
      } catch (error) {
        console.error("获取公告数据失败:", error);
        this.$message.error("获取公告数据失败");
      } finally {
        this.loading = false;
      }
    },

    // 获取部门名称
    getDeptName(deptId) {
      if (!deptId) return "-";
      const dept = this.deptOptions.find((item) => item.id === deptId);
      return dept ? dept.name : "-";
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 0:
          return "未发布";
        case 1:
          return "已发布";
        case 2:
          return "已撤销";
        default:
          return "未知";
      }
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case 0:
          return "warning";
        case 1:
          return "success";
        case 2:
          return "info";
        default:
          return "";
      }
    },

    // 查询按钮点击事件
    handleSearch() {
      this.pagination.current = 1;
      this.fetchData();
    },

    // 重置查询条件
    resetSearch() {
      this.searchForm = {
        id: null,
        title: "",
        deptId: null,
        status: null,
      };
      this.pagination.current = 1;
      this.fetchData();
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size;
      this.fetchData();
    },

    // 当前页改变
    handleCurrentChange(current) {
      this.pagination.current = current;
      this.fetchData();
    },

    // 显示新增对话框
    showAddDialog() {
      this.dialogType = "add";
      this.dialogTitle = "新增公告";
      this.noticeForm = {
        id: null,
        deptId: null,
        title: "",
        content: "",
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.noticeFormRef?.clearValidate();
      });
    },

    // 查看公告
    async handleView(row) {
      try {
        const res = await viewNoticeContent({ id: row.id });
        this.currentNotice = {
          title: res.result.title,
          content: res.result.content,
          deptName: this.getDeptName(res.result.deptId),
          status: this.getStatusText(res.result.status),
        };
        this.viewDialogVisible = true;
      } catch (error) {
        console.error("查看公告失败:", error);
        this.$message.error("查看公告失败");
      }
    },

    // 编辑公告
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogTitle = "编辑公告";
      this.noticeForm = {
        id: row.id,
        deptId: row.deptId,
        title: row.title,
        content: row.content,
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.noticeFormRef?.clearValidate();
      });
    },

    // 提交编辑
    async handleEditSubmit() {
      try {
        await this.$refs.noticeFormRef.validate();

        const { id, deptId, title, content } = this.noticeForm;
        await editNotice({ id, deptId, title, content });

        this.$message.success("编辑成功");
        this.dialogVisible = false;
        this.fetchData();
      } catch (error) {
        console.error("编辑失败:", error);
        if (error !== "validate") {
          this.$message.error("编辑失败");
        }
      }
    },

    // 保存公告（新增）
    async handleSave() {
      try {
        await this.$refs.noticeFormRef.validate();

        const { deptId, title, content } = this.noticeForm;
        await publishNotice({ deptId, title, content, status: 0 });

        this.$message.success("保存成功");
        this.dialogVisible = false;
        this.fetchData();
      } catch (error) {
        console.error("保存失败:", error);
        if (error !== "validate") {
          this.$message.error("保存失败");
        }
      }
    },

    // 发布公告（新增）
    async handlePublishDialog() {
      try {
        await this.$refs.noticeFormRef.validate();

        const { deptId, title, content } = this.noticeForm;
        await publishNotice({ deptId, title, content, status: 1 });

        this.$message.success("发布成功");
        this.dialogVisible = false;
        this.fetchData();
      } catch (error) {
        console.error("发布失败:", error);
        if (error !== "validate") {
          this.$message.error("发布失败");
        }
      }
    },

    // 发布公告
    async handlePublish(row) {
      try {
        await this.$confirm(`确定要发布该公告吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        await changeNoticeStatus({ id: row.id, status: 1 });
        this.$message.success(`发布成功`);
        this.fetchData();
      } catch (error) {
        console.error(`发布失败:`, error);
        if (error !== "cancel") {
          this.$message.error(`发布失败`);
        }
      }
    },

    // 删除公告
    async handleDelete(row) {
      try {
        await this.$confirm("确定要删除该公告吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        await deleteNotice({ id: row.id });
        this.$message.success("删除成功");
        this.fetchData();
      } catch (error) {
        console.error("删除失败:", error);
        if (error !== "cancel") {
          this.$message.error("删除失败");
        }
      }
    },
  },
};
</script>
    
    <style scoped>
.draft-notice-container {
  padding: 0 20px;
  height: 85%;
  display: flex;
  flex-direction: column;
}

.search-form {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.notice-table {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
  background: #fff;
  padding: 10px 20px;
  border-radius: 4px;
}

.notice-detail-container {
  padding: 0 20px;
}

.notice-title {
  text-align: center;
  margin-bottom: 16px;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

.notice-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  color: #909399;
  font-size: 14px;
}

.notice-content {
  padding: 0 10px;
  line-height: 1.8;
  font-size: 15px;
  color: #606266;
}

.notice-content >>> p {
  margin: 10px 0;
}

.notice-content >>> img {
  max-width: 100%;
  display: block;
  margin: 10px auto;
}
</style>